package huaweiod.first;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 华为机试真题 Java 实现【寻找路径】【2022.11 Q4 新题】
 * 3 5 7 -1 -1 2 4
 * 3 7 2
 * <p>
 * 5 9 8 -1 -1 7 -1 -1 -1 -1 -1 6
 * 5 8 7 6
 */
public class A_2023_54_FindPath {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<Integer> collect = Arrays.stream(in.nextLine().split(" "))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        // 查找叶子节点（位置、值）
        PriorityQueue<Integer[]> pq = new PriorityQueue<>(new Comparator<Integer[]>() {
            @Override
            public int compare(Integer[] o1, Integer[] o2) {
                return o1[1] - o2[1];
            }
        });
        int n = collect.size();
        for (int i = 1; i <= n; i++) {
            Integer value = collect.get(i - 1);
            if (value == -1) {
                continue;
            }
            // 存在左节点
            if (2 * i <= n && collect.get(2 * i - 1) != -1) {
                continue;
            }
            // 存在右节点
            if (2 * i + 1 <= n && collect.get(2 * i) != -1) {
                continue;
            }
            pq.add(new Integer[]{i, collect.get(i - 1)});
        }
        List<Integer> res = new ArrayList<>();
        Integer[] peek = pq.poll();
        if (peek == null) return;
        Integer index = peek[0];
        while (index != 0) {
            res.add(collect.get(index - 1));
            index = index / 2;
        }
        StringJoiner sj = new StringJoiner(" ");
        for (int i = res.size() - 1; i >= 0; i--) {
            sj.add(String.valueOf(res.get(i)));
        }
        System.out.println(sj);
    }
}
